<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear='getGoodsList' @change='getGoodsList'>
            <el-button slot="append" icon="el-icon-search" @click="getGoodsList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <!-- <el-button type="primary" @click="addGoodsBtn">添加商品</el-button> -->
          <el-button type="primary" @click="goToAddPage">添加商品</el-button>
        </el-col>
      </el-row>
      <!-- 商品列表区域 -->
      <el-table :data="goodslist" stripe border style="width: 100%">
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="goods_name" label="商品名称" min-width="180px">
        </el-table-column>
        <el-table-column prop="goods_price" label="商品价格(元)" min-width="95px">
        </el-table-column>
        <el-table-column prop="goods_weight" label="商品重量" min-width="70px">
        </el-table-column>
        <el-table-column label="创建时间" min-width="140px">
          <template v-slot:default='scope'>
            {{dateFormat(scope.row.add_time)}}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="140px">
          <template v-slot:default='scope'>
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showModifyDialog(scope.row.goods_id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeGoods(scope.row.goods_id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 页码区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[5, 10, 20, 30]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
      <!-- 修改商品区域 -->
      <el-dialog title="修改用户信息" :visible.sync="dialogModifyVisible" width="50%" @close="resetModifyForm">
        <el-form ref="modifyFormRef" :model="modify_form" :rules="rules" label-width="120px">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="modify_form.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="选择商品分类" prop="goods_cat">
            <el-cascader v-model="selectCatId" :options="classlist" :props="{ expandTrigger: 'hover', label:'cat_name', value:'cat_id' }" @change="classModifyChange" clearable></el-cascader>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input v-model="modify_form.goods_price"></el-input>
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_number">
            <el-input v-model="modify_form.goods_number"></el-input>
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight">
            <el-input v-model="modify_form.goods_weight"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogModifyVisible = false">取 消</el-button>
          <el-button @click="resetModifyForm">重置</el-button>
          <el-button type="primary" @click="modifyGoods">确 定</el-button>
        </div>
      </el-dialog>
      <!--  添加商品区域
      <el-dialog title="添加商品" :visible.sync="dialogVisible" width="50%" @close="resetForm">
        <el-form ref="addFormRef" :model="add_form" :rules="rules" label-width="120px">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="add_form.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="选择商品分类" prop="goods_cat">
            <el-cascader v-model="selectCatId" :options="classlist" :props="{ expandTrigger: 'hover', label:'cat_name', value:'cat_id' }" @change="classAddChange" clearable></el-cascader>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input v-model="add_form.goods_price" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_number">
            <el-input v-model="add_form.goods_number" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight">
            <el-input v-model="add_form.goods_weight" type="number"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="addGoods">确 定</el-button>
        </span>
      </el-dialog> -->
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'MyList',
  data() {
    return {
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 5
      },
      goodslist: [],
      classlist: [],
      selectCatId: [],
      /* add_form: {
        goods_name: '',
        goods_cat: '',
        goods_price: '',
        goods_number: '',
        goods_weight: ''
      }, */
      modify_form: {},
      total: 0,
      // dialogVisible: false,
      dialogModifyVisible: false,
      rules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getGoodsList()
  },
  methods: {
    // 格式化时间
    dateFormat(ValDate) {
      const date = new Date(ValDate * 1000)
      const y = date.getFullYear()
      const m = this.addZero(date.getMonth() + 1)
      const d = this.addZero(date.getDate())
      const HH = this.addZero(date.getHours())
      const MM = this.addZero(date.getMinutes())
      const SS = this.addZero(date.getSeconds())
      return `${y}-${m}-${d} ${HH}:${MM}:${SS}`
    },
    // 为时间补零
    addZero(e) {
      return (e = e > 10 ? e : '0' + e)
    },
    // 获取商品列表
    async getGoodsList() {
      const { data: res } = await this.$http.get('/goods', { params: this.queryInfo })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品列表失败！')
      }
      this.goodslist = res.data.goods
      this.total = res.data.total
      // console.log(this.goodslist)
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.queryInfo.pagesize = val
      this.getGoodsList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页在第 ${val} 页`)
      this.queryInfo.pagenum = val
      this.getGoodsList()
    },
    // 获取商品分类数据列表
    async getClassList() {
      const { data: res } = await this.$http.get('/categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据列表失败！')
      }
      this.classlist = res.data
    },
    /* // 重置添加商品表单
    resetForm() {
      this.$refs.addFormRef.resetFields()
      this.selectCatId = []
    },
    // 添加商品按钮
    addGoodsBtn() {
      this.dialogVisible = true
      this.getClassList()
    },
    // 将新选择分类项的id值数组转换为字符串，存入添加表单中
    classAddChange() {
      // console.log(this.selectCatId)
      this.add_form.goods_cat = this.selectCatId.join(',')
      // console.log(this.add_form)
    },
    // 添加商品
    addGoods() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('/goods', this.add_form)
        if (res.meta.status !== 201) {
          return this.$message.error('添加商品失败')
        }
        this.$message.success('添加商品成功')
        this.dialogVisible = false
        this.getGoodsList()
      })
    }, */
    // 前往添加商品页面
    goToAddPage() {
      this.$router.push('/goods/add')
    },
    // 重置修改商品信息表单
    resetModifyForm() {
      this.$refs.modifyFormRef.resetFields()
      this.selectCatId = []
    },
    // 根据id查询商品信息
    async showModifyDialog(id) {
      this.dialogModifyVisible = true
      this.getClassList()
      const { data: res } = await this.$http.get('/goods/' + id)
      if (res.meta.status !== 200) return
      this.modify_form = res.data
      // console.log(this.modify_form)
      // 将修改表单中已选择分类项的id值字符串转换为数组，存入中selectCatId
      this.selectCatId = this.modify_form.goods_cat.split(',')
    },
    // 将新选择分类项的id值数组转换为字符串，存入修改表单中
    classModifyChange() {
      this.modify_form.goods_cat = this.selectCatId.join(',')
      // console.log(this.modify_form)
    },
    // 修改商品信息
    modifyGoods() {
      this.$refs.modifyFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('/goods/' + this.modify_form.goods_id, {
          goods_name: this.modify_form.goods_name,
          goods_price: this.modify_form.goods_price,
          goods_number: this.modify_form.goods_number,
          goods_weight: this.modify_form.goods_weight,
          goods_cat: this.modify_form.goods_cat
        })
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('修改商品信息失败')
        }
        this.dialogModifyVisible = false
        this.getGoodsList()
        this.$message.success('修改商品信息成功')
      })
    },
    // 删除商品
    removeGoods(id) {
      // 弹框提示
      this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const { data: res } = await this.$http.delete('/goods/' + id)
          if (res.meta.status === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
          this.getGoodsList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>

<style lang='less' scoped>
.el-cascader {
  width: 100%;
}
</style>
